//
//  gamepad.cpp
//  Sinnca Engine v2
//
//  Created by Ryan Oldis on 12/6/11.
//  Copyright (c) 2011 Sinnca Studios. All rights reserved.
//

#include "input.h"

#include "script.h"

gamePad::gamePad()
{
	joystick = SDL_JoystickOpen(0);
	
	if (joystick != NULL)
	{
		name = SDL_JoystickName(0);
	} else {
		name = "No controller connected.\n";
	}
	
	
	for (int i = 0; i < SDL_JoystickNumAxes(joystick); i++)
	{
		axies.push_back(0.0);
		
	}
	for (int i = 0; i < SDL_JoystickNumButtons(joystick); i++)
	{
		buttons.push_back(0);
	}
	
	Script->setVar("noOfAxies", SDL_JoystickNumAxes(joystick));
	Script->setVar("noOfButtons", SDL_JoystickNumButtons(joystick));
	
}

gamePad::~gamePad()
{
	if (joystick != NULL)
	{
		SDL_JoystickClose(joystick);
	}
	
}

void gamePad::printInfo()
{
	printf("Controller: %s\n", name.c_str());
	if (joystick != NULL)
	{
		printf("Axies: %d\n", SDL_JoystickNumAxes(joystick));
		printf("Buttons: %d\n", SDL_JoystickNumButtons(joystick));
		printf("Hats: %d\n", SDL_JoystickNumHats(joystick));
		printf("Balls: %d\n", SDL_JoystickNumBalls(joystick));
	}
	
}

int l_buttonDown(lua_State* L)
{
	if (input->pad.joystick != NULL)
	{
		
		int i = (int)lua_tointeger(L, -1);
		if (i > SDL_JoystickNumButtons(input->pad.joystick))
		{
			lua_pushnil(L);
			printf("buttonDown: that button doesn't exist. Try a lower number.\n");
		} else {
			lua_pushinteger(L, input->pad.buttons[i]);
		}
		
	} else {
		lua_pushnumber(L, 0);
	}
	return 1;
}
int l_analogAxis(lua_State* L)
{
	if (input->pad.joystick != NULL)
	{
		int i = (int)lua_tointeger(L, -1);
		
		if (i > SDL_JoystickNumAxes(input->pad.joystick))
		{
			lua_pushnumber(L, 0);
			printf("analogAxis: that axis doesn't exist. Try a lower number.\n");
		} else {
			lua_pushnumber(L, input->pad.axies[i]);
		}
	} else {
		lua_pushnumber(L, 0);
	}
	
	return 1;
}

int l_reInitGamepad(lua_State* L)
{
	/*
	joystick = SDL_JoystickOpen(0);
	
	if (joystick != NULL)
	{
		name = SDL_JoystickName(0);
	} else {
		name = "No controller connected.\n";
	}
	
	
	for (int i = 0; i < SDL_JoystickNumAxes(joystick); i++)
	{
		axies.push_back(0.0);
		
	}
	for (int i = 0; i < SDL_JoystickNumButtons(joystick); i++)
	{
		buttons.push_back(0);
	}
	
	Script->setVar("noOfAxies", SDL_JoystickNumAxes(joystick));
	Script->setVar("noOfButtons", SDL_JoystickNumButtons(joystick));
	*/
	lua_pushnumber(L, 0);
	return 1;
}